import os
import psycopg2.extras
from QRoute import QRoute
from PyQt5 import QtWidgets
from PyQt5.QtCore import QDateTime, QTimer
from PyQt5.QtWidgets import QApplication, QWidget, QMessageBox, QMainWindow, QStatusBar, QLabel, QAction
from ui import LoginDialog
from Page import Dashboard

class Widget(QWidget, QRoute.RouteSignal):
    def __init__(self, parent=None):
        super(Widget, self).__init__()
        self.setting = parent[0]
        self.unit = parent[1]
        self.ui_login = LoginDialog.Ui_LoginDialog()
        self.ui_login.setupUi(self)
        self.ui_login.retranslateUi(self)
        self.connectChange()
        self.ui_login.lineEdit_username.setText('GadflyBSD')
        self.ui_login.lineEdit_password.setText('xx123456')

    def pgsqlStatus_timeout(self):
        try:
            conn = self.unit.dbConnect(self.setting.pgsql)
            self.ui_login.pgsqlStatusLabel.setText("连接成功！")
            return True
        except Exception as e:
            self.ui_login.pgsqlStatusLabel.setText("连接失败: " + str(e))
            return False
        finally:
            self.unit.dbDisconnect(conn)

    def timer_timeout(self):  # 定时中断相应500
        curTime = QDateTime.currentDateTime()  # 获取当前时间
        timePlay = curTime.toString('yyyy年MM月dd日 dddd hh:mm:ss')
        self.ui_login.dateTimeLabel.setText(timePlay)

    def connectChange(self):
        self.timer = QTimer()  # 创建定时器
        self.timer.start(1000)  # 定时周期1000ms
        self.timer.timeout.connect(self.timer_timeout)
        if(self.pgsqlStatus_timeout()):
            self.pgsqlStatus = QTimer()
            self.pgsqlStatus.start(15000)
            self.pgsqlStatus.timeout.connect(self.pgsqlStatus_timeout)


    def accept(self):
        if (len(self.ui_login.lineEdit_username.text()) == 0):
            QMessageBox.warning(self, "操作失败", '登录用户名或手机号码、电子邮件没有填写！')
            return
        if (len(self.ui_login.lineEdit_password.text()) == 0):
            QMessageBox.warning(self, "操作失败", '登录用户密码没有填写！')
            return
        try:
            conn = self.unit.dbConnect(self.setting.pgsql)
            cursor = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
            cursor.execute("SELECT trading.func_user_password_check('%s', '%s') AS result"
                           % (self.ui_login.lineEdit_username.text(), self.ui_login.lineEdit_password.text()))
            result = dict(cursor.fetchone())['result']
            if(result['status'] == 'Success'):
                QMessageBox.about(self, "操作成功", "登录用户和密码校验成功！")
                self.close()
                cursor.execute("SELECT code, upid, kind, label, regexp, description FROM trading.dictionary")
                dictionary = [dict(row) for row in cursor.fetchall()]
                cursor.execute("SELECT uuid, account_type, account_label, balance, is_default FROM trading.account WHERE owner_id = '%s';" % result['data']['uuid'])
                account = [dict(row) for row in cursor.fetchall()]
                self.signal.emit(Dashboard.Widget, (self.setting, self.unit, result['data'], account, dictionary))
            else:
                QMessageBox.warning(self, "操作失败", str(result.msg))
        except Exception as e:
            QMessageBox.warning(self, "操作失败", str(e))
        finally:
            self.unit.dbDisconnect(conn)

    def reject(self):
        reply = QMessageBox.question(self, "是否确认？", "你真的要取消登录退出系统吗？", QMessageBox.Yes | QMessageBox.Cancel)
        if (reply == QMessageBox.Yes):
            self.close()